#include "DXEngineTimer.h"



CDXEngineTimer::CDXEngineTimer()
{
	LARGE_INTEGER m_HwPerfFreq;

	if (QueryPerformanceFrequency(&m_HwPerfFreq))
	{
		m_PerfHardware = TRUE;
		QueryPerformanceCounter(&m_HwLastTime);
		m_TimeScale = 1.0f / m_HwPerfFreq.QuadPart;
	}
	else
	{
		
		m_PerfHardware = FALSE;
		m_SwLastTime = timeGetTime();
		m_TimeScale = 0.001f;
	}
	SetFPSLock(g_f_timerDefault_Fps);
}




CDXEngineTimer::~CDXEngineTimer()
{
}



void CDXEngineTimer::SetFPSLock(float fFrameperSecond)
{
	m_TimePerFrame = 1.0f / fFrameperSecond;
}



bool CDXEngineTimer::HwTick()
{
	float fTimeElapsed = getHwTimeElapsed();

	if (fTimeElapsed < m_TimePerFrame)
	{
		return false;
	}
	resetTimer();
	return true;
}



bool CDXEngineTimer::SwTick()
{
	float fTimeElapsed = getSwTimeElapsed();

	if (fTimeElapsed < m_TimePerFrame)
	{
		return false;
	}
	resetTimer();
	return true;
}



bool CDXEngineTimer::Tick()
{
	if ( isHardwareTimer() )
	{
		return (HwTick());
	}
	else
	{
		return (SwTick());
	}
}



float  CDXEngineTimer::getHwTimeElapsed()
{
	float fTimeElapsed;

	QueryPerformanceCounter(&m_HwCurrentTime);
	fTimeElapsed = (m_HwCurrentTime.QuadPart - m_HwLastTime.QuadPart) * m_TimeScale;
	return fTimeElapsed;
}


float  CDXEngineTimer::getSwTimeElapsed()
{
	float fTimeElapsed;

	m_SwCurrentTime = timeGetTime();
	fTimeElapsed = (m_SwCurrentTime - m_SwLastTime) * m_TimeScale;
	return fTimeElapsed;
}




void CDXEngineTimer::resetTimer()
{
	m_SwLastTime = m_SwCurrentTime;
	m_HwLastTime = m_HwCurrentTime;
}



bool  CDXEngineTimer::isHardwareTimer()
{
	if (m_PerfHardware)
		return true;
	return false;
}


float  CDXEngineTimer::getTimeElapsed()
{
	if (m_PerfHardware)
		return getHwTimeElapsed();
	return getSwTimeElapsed();
}



float  CDXEngineTimer::getCurTime()
{
	if (m_PerfHardware)
		return m_HwCurrentTime.QuadPart * m_TimeScale;
	return m_SwCurrentTime * m_TimeScale;
}
